
let timeSecond = 1*1000 //记录页面时间间隔 单位ms
let whiteHtmlList = [ //记录页面白名单
  '/vplay/index.html',
  '/vplay/new.html',
  '/vplay/',
  '/vplay'
]
let timestamp = Date.now() // 时间戳
let htmlMap = {} //记录用户请求页面map

function getRemoteIp(req) {
  try {
    let xForwardedFor = req.headers['x-forwarded-for']
    if (xForwardedFor) {
      let xForwardedForList = xForwardedFor.split(',')
      if (xForwardedForList && xForwardedForList.length) {
        return xForwardedForList[0]
      }
    } else {
      return req.headers['remote_addr'] || req.headers['remoteip']
    }
  } catch (error) {
    
  }

  return null
}

module.exports = async (req, res, next) => {

  let path = req.path || '/'
  var isMatch  = /^\/vplay/.test(path) 
  if (isMatch && whiteHtmlList.includes(path)){
    let requestTime = Date.now();
    let remoteAddr = getRemoteIp(req)

    if (!remoteAddr) await next()

    if (requestTime - timestamp >= timeSecond) { //每隔时间间隔清空htmlMap,并且重置时间戳
      htmlMap = {};
      timestamp = requestTime
    }
    let key = path + '_' + remoteAddr
    if (!htmlMap[key]) {
      htmlMap[key] = 0
    }
    if (htmlMap[key] > 2) { //规定时间间隔内超过3次返回状态502
      return res.status(502).end()
    }
    htmlMap[key] += 1
  }

  await next()
}